﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using UPos.Codes;
using D = System.Drawing;
using UPos.Core;
using UPos.Core.LogProvider;
using System.Resources;

namespace UPos
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        NotifyIcon Notify { get; set; }

        bool CancelClose { get; set; }

        Timer Timer { get; set; }

        bool _uploading;
        bool Uploading
        {
            get { return _uploading; }
            set
            {
                _uploading = value;
                this.Dispatcher.Invoke(() => tbMessage.Text = value ? "数据正在上传中" : Timer.Enabled ? "计时器正常运行" : "计时器等待中");
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            // 创建托盘图标
            Notify = new NotifyIcon
            {
                Text = "静安嘉里数据上传 - 监控台",
                // 从资源中读取图标
                Icon = (D.Icon)new ResourceManager("UPos.Properties.Resources", this.GetType().Assembly).GetObject("ni"),
                Visible = true,
                ContextMenuStrip = new ContextMenuStrip()
            };
            // 添加显示按钮到托盘
            var item = new ToolStripMenuItem("显示控制台");
            item.Click += Show_Notify_Item;
            Notify.ContextMenuStrip.Items.Add(item);
            // 添加分割线
            Notify.ContextMenuStrip.Items.Add(new ToolStripSeparator());
            // 添加退出按钮
            item = new ToolStripMenuItem("退出");
            item.Click += Exit_Notify_Item;
            Notify.ContextMenuStrip.Items.Add(item);
            // 指定每次关闭都取消，直到使用指定的方式关闭
            CancelClose = true;
            // 从配置文件获取计时器的触发间隔
            var sInterval = ConfigurationManager.AppSettings["Interval"];
            if (string.IsNullOrWhiteSpace(sInterval))
                throw new ConfigurationErrorsException("缺少 AppSettings 项 Interval");
            // 换算成毫秒
            var iInterval = int.Parse(sInterval);
            iInterval = iInterval * 60 * 1000;
            // 创建计时器
            Timer = new Timer { Interval = iInterval };
            Timer.Tick += Timer_Tick;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (!Uploading)
            {
                Uploading = true;
                Task.Run(() =>
                {
                    Serv.Upload();
                    Uploading = false;
                });
                tbTime.Text = DateTime.Now.AddSeconds(Timer.Interval / 1000).ToString("HH:mm:ss");
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // 注册日志添加事件，在每次出现新日志时，显示到界面上
            LogSQLite.Writed += LogSQLite_Writed;
            // 绑定日志数据远
            this.DataContext = new ObservableCollection<Log>();

            Task.Run(() =>
            {
                // 程序启动后执行第一次数据处理
                // 检查前一天的所有数据是否都正确上传
                Serv.UploadLastDay();
            });

            // 从配置读取是否自动启动计时器
            var autoStart = ConfigurationManager.AppSettings["AutoStart"];
            int iAutoStart = 1;
            // 如果没有配置，则默认自动启动
            if (!string.IsNullOrWhiteSpace(autoStart))
                iAutoStart = int.Parse(autoStart);
            if (iAutoStart > 0)
            {
                tbTime.Text = DateTime.Now.AddSeconds(Timer.Interval / 1000).ToString("HH:mm:ss");
                // 启动计时器
                Timer.Start();
                tbMessage.Text = "计时器正常初始化并启动";
            }
            else
            {
                tbMessage.Text = "计时器正常初始化并等待手动启动";
            }

            // 从配置读取是否自动隐藏
            var autoHide = ConfigurationManager.AppSettings["AutoHide"];
            int iAutoHide = 1;
            // 如果没有配置，则默认自动隐藏
            if (!string.IsNullOrWhiteSpace(autoHide))
                iAutoHide = int.Parse(autoHide);
            if (iAutoHide > 0)
            {
                this.WindowState = System.Windows.WindowState.Minimized;
                this.ShowInTaskbar = false;
                this.Hide();

                if (iAutoStart < 1)
                {
                    Notify.ShowBalloonTip(5000, "注意", "计时器当前没有被配置为自动启动，需要手动启动！", ToolTipIcon.Warning);
                }
            }
        }

        private void Show_Notify_Item(object sender, EventArgs e)
        {
            this.Show();
            this.ShowInTaskbar = true;
            this.WindowState = System.Windows.WindowState.Normal;
        }

        private void Exit_Notify_Item(object sender, EventArgs e)
        {
            CancelClose = false;
            this.Close();
        }

        private void LogSQLite_Writed(string message, string result, DateTime datetime)
        {
            this.Dispatcher.Invoke(() =>
            {
                var source = this.DataContext as ObservableCollection<Log>;
                if (source != null)
                {
                    source.Insert(0, new Log
                    {
                        message = message,
                        result = result,
                        DateTime = datetime
                    });
                }
            });
        }

        private void History_Button_Click(object sender, RoutedEventArgs e)
        {
            Window1 win = new Window1();
            win.ShowDialog();
        }

        private void window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (CancelClose)
            {
                e.Cancel = true;
                this.WindowState = System.Windows.WindowState.Minimized;
                this.ShowInTaskbar = false;
                this.Hide();
            }
            else
            {
                Notify.Visible = false;
            }
        }

        private void Exit_Item_Click(object sender, RoutedEventArgs e)
        {
            CancelClose = false;
            this.Close();
        }

        private void Startup_Item_Click(object sender, RoutedEventArgs e)
        {
            Timer.Start();
            tbMessage.Text = "计时器已正常启动";
            tbTime.Text = DateTime.Now.AddSeconds(Timer.Interval / 1000).ToString("HH:mm:ss");
        }

        private void Stop_Item_Click(object sender, RoutedEventArgs e)
        {
            Timer.Stop();
            tbMessage.Text = "计时器已正常停止";
            tbTime.Text = "00:00:00";
        }

        private void window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.F12 && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift))
            {
                menuTest.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void Upload_Item_Click(object sender, RoutedEventArgs e)
        {
            DatePicker picker = new DatePicker();
            var result = picker.ShowDialog();
            if (result.HasValue && result.Value && picker.date1.SelectedDate.HasValue)
            {
                if (!Uploading)
                {
                    var date = picker.date1.SelectedDate.Value;
                    Uploading = true;
                    Task.Run(() =>
                    {
                        Serv.TestUpload(date);
                        Uploading = false;
                    });
                }
            }
        }
    }
}
